import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * UDP 提供者，用于提供服务
 */
public class UDPProvider {
    public static void main(String[] args) throws IOException {
        System.out.println("UDPProvider Started.");

        // 作为接收者，指定一个端口用于数据接收
        DatagramSocket datagramSocket = new DatagramSocket(20000);

        // 构建接收实体
        final byte[] buf = new byte[512];
        DatagramPacket receivePack = new DatagramPacket(buf, buf.length);

        /**
         * 接收
         */
        datagramSocket.receive(receivePack);

        // 打印接收到的信息与发送者的信息
        // 发送者的IP地址
        String ip = receivePack.getAddress().getHostAddress();
        // 发送者的端口
        int port = receivePack.getPort();
        // 数据大小
        int dataLen = receivePack.getLength();

        String data = new String(receivePack.getData(), 0, dataLen); // 假设报文内容都是String
        System.out.println("UDPProvider receive from ip:" + ip + "\tport:" + port + "\tdata:" + data);

        /**
         * 构建一份回送数据
         */
        String responseData = "Receive data with len:" + dataLen;
        byte[] responseDataBytes = responseData.getBytes(); // 未设定字符集

        // 直接根据发送者构建一个回送报文
        DatagramPacket responsePack =  new DatagramPacket(responseDataBytes,
                responseDataBytes.length, receivePack.getAddress(), receivePack.getPort());

        datagramSocket.send(responsePack);

        /**
         * 完成
         */
        System.out.println("UDPProvider Finished");
        datagramSocket.close();
    }
}
